package ca.cbc.medialib.service;

import java.net.URI;
import java.net.URISyntaxException;

import ca.cbc.medialib.Bootstrap;
import ca.cbc.medialib.entity.MediaFile;
import ca.cbc.medialib.exception.ThePlatformObjectNotFoundException;
import com.google.common.base.Function;
import com.theplatform.data.api.DataObjectField;
import com.theplatform.data.api.exception.ObjectNotFoundException;
import com.theplatform.media.api.fields.MediaFileField;;

/**
 * =============================================
 * Copyright (c) 2011 Canadian Broadcasting Corporation.
 * All rights reserved.
 * <p/>
 * ca.cbc.medialib.service.MediaFileService.java
 * =============================================
 * <p/>
 * PURPOSE:	Manages communicate with thePlatform for MediaFile
 * <p/>
 * =============================================
 * MODIFICATION		LOG	DATE		REASON / Change Request #
 * Jordan Xu	 March 5th, 2012	Initial file creation
 * =============================================
 */

public final class MediaFileService extends EntityService {
    private static String[] mediaFileFieldParams = new String[]{
            DataObjectField.id.toString(),
            MediaFileField.filePath.toString(),
            MediaFileField.storageUrl.toString(),
            MediaFileField.duration.toString(),
            MediaFileField.contentType.toString()
    };
    
    private Function<com.theplatform.media.api.data.objects.MediaFile, MediaFile> convertMediaFile = new Function<com.theplatform.media.api.data.objects.MediaFile, MediaFile>() {
        @Override
        public MediaFile apply(com.theplatform.media.api.data.objects.MediaFile mediaFile) {
            
        	String originalFileName = null;
        	String filePath = mediaFile.getFilePath();
        	
        	//get file name
        	String tmpStr = filePath;
        	if (tmpStr != null) {
        		int startIndex = tmpStr.lastIndexOf("/") + 1;
        		int endIndex = tmpStr.lastIndexOf(".");
        		if (startIndex < endIndex)
        			tmpStr = tmpStr.substring(startIndex, endIndex);
            }
        	
        	//In case of duplicate video, remove the junk theP attaches to it.
        	if(tmpStr!= null && tmpStr.length() > 8 && tmpStr.substring(tmpStr.length()-8, tmpStr.length()).matches("__[\\d]{6}")) {
        		tmpStr = tmpStr.substring(0, tmpStr.length()-8);
            }
        	
            String suffix = filePath.substring(filePath.lastIndexOf("."), filePath.length());
            
            if (suffix.equals(".flv")){
            	originalFileName = tmpStr + ".mp4";
            } else {
            	originalFileName = tmpStr + suffix;
            }    	
        	
            return new MediaFile(zeroOrLong(removePrefix(nullOrString(mediaFile.getId()))),
            		nullOrString(getDurationAsString(mediaFile.getDuration())),
            		originalFileName);
        }
    };

    public MediaFile get(long id) throws ThePlatformObjectNotFoundException {
        try {
            com.theplatform.media.api.data.objects.MediaFile r = Bootstrap.instance.getMediaFileClient().get(
                    new URI(String.valueOf(id)),
                    mediaFileFieldParams
            );
            return convertMediaFile.apply(r);
        } catch (URISyntaxException e) {
            throw new ThePlatformObjectNotFoundException("Media File URI Syntex Error", e);
        } catch (ObjectNotFoundException e) {
            throw new ThePlatformObjectNotFoundException("Media File object not found", e);
        }
    }
}
